package com.redisMq.producer.service;


import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RedisMqSendService {

    private final Gson gson = new Gson();

    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public RedisMqSendService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private final Map<String, Object> okMap = new HashMap<String, Object>() {{
        put("success", true);
    }};
    private final Map<String, Object> noMap = new HashMap<String, Object>() {{
        put("success", false);
    }};

    /**
     * 发送消息
     */
    public Map<String, Object> sendMessage(String topicName, Map<String, Object> msgMap) {
        try {
            redisTemplate.convertAndSend(topicName, gson.toJson(msgMap));
            return okMap;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("发送RedisMq消息失败:" + e.getMessage());
            noMap.put("message", e.getMessage());
            return noMap;
        }
    }

}
